<!-- 修改密码 -->
<template>
  <el-dialog title="修改密码" :loading="loading" v-model="visible" width="500px" append-to-body :before-close="cancel">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="旧密码" prop="old_password" :rules="[]">
        <el-input v-model="form.old_password" type="password" placeholder="请输入旧密码" />
      </el-form-item>
      <el-form-item label="新密码" prop="new_password" :rules="[]">
        <el-input v-model="form.new_password" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="new_password2" :rules="[]">
        <el-input v-model="form.new_password2" type="password" placeholder="请再次输入新密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="ChangePasswd">
import useUserStore from "@/store/modules/user";
import { editPasswd } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const store = useUserStore();

const visible = defineModel(false);
const loading = ref(false);

const form = reactive({
  id: store.id,
  old_password: "",
  new_password: "",
  new_password2: ""
});
const passwdValidate = (rule, value, cb) => {
  if (!value) {
    cb(new Error("请输入新密码"));
  } else if (form.new_password2 && value !== form.new_password2) {
    cb(new Error("两次输入不一致，请确认"));
  } else {
    cb();
  }
};
const passwdConfirm = (rule, value, cb) => {
  if (!value) {
    cb(new Error("请再次输入新密码"));
  } else if (form.new_password && value !== form.new_password) {
    cb(new Error("两次输入不一致，请确认"));
  } else {
    cb();
  }
};
const rules = reactive({
  old_password: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  new_password: [{ required: true, validator: passwdValidate, trigger: "blur" }],
  new_password2: [{ required: true, validator: passwdConfirm, trigger: "blur" }]
});

function cancel() {
  clearForm();
  visible.value = false;
}
async function submitForm() {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (!valid) return;
    const params = {
      id: store.id,
      new_password: form.new_password,
      old_password: form.old_password
    };
    const res = await editPasswd(params);
    if (res.code === 0) {
      proxy.$modal.msgSuccess("修改成功");
      cancel();
      return;
    }
    proxy.$modal.msgError(res.message);
  });
}
function clearForm() {
  proxy.$refs["formRef"].resetFields();
  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
}
</script>
